<template>
  <el-card v-loading="loading">
    <template #header>
      <div class="card-header">
        <span>访客趋势</span>
        <el-radio-group v-model="days" size="small" @change="fetchData">
          <el-radio-button :label="7">周</el-radio-button>
          <el-radio-button :label="30">月</el-radio-button>
          <el-radio-button :label="365">年</el-radio-button>
        </el-radio-group>
      </div>
    </template>
    <div ref="chartRef" class="chart"></div>
  </el-card>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch } from 'vue'
import * as echarts from 'echarts'
import { getVisitorTrend } from '@/api/visitor'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'

interface VisitData {
  date: string
  count: number
}

const loading = ref(false)
const days = ref(7)
const chartRef = ref<HTMLElement | null>(null)
let chartInstance: echarts.ECharts | null = null

const initChart = () => {
  if (!chartRef.value) return
  
  chartInstance = echarts.init(chartRef.value)
}

const updateChart = (data: VisitData[]) => {
  if (!chartInstance) return

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: (params: any) => {
        const data = params[0]
        return `${dayjs(data.name).format('YYYY-MM-DD HH:mm:ss')}<br/>访客数：${data.value}`
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: data.map(item => dayjs(item.date).format('YYYY-MM-DD HH:mm:ss')),
      axisTick: {
        alignWithLabel: true
      },
      axisLabel: {
        formatter: (value: string) => {
          return dayjs(value).format('MM-DD HH:mm')
        },
        interval: 0,
        rotate: 45
      }
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '访客数',
        type: 'line',
        smooth: true,
        data: data.map(item => item.count),
        itemStyle: {
          color: '#409EFF'
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {
              offset: 0,
              color: 'rgba(64,158,255,0.3)'
            },
            {
              offset: 1,
              color: 'rgba(64,158,255,0.1)'
            }
          ])
        }
      }
    ]
  }
  
  chartInstance.setOption(option)
}

const fetchData = async () => {
  loading.value = true
  try {
    const res = await getVisitorTrend(days.value)
    updateChart(res.data)
  } catch (error) {
    console.error('获取访客趋势数据失败:', error)
    ElMessage.error('获取访客趋势数据失败')
  } finally {
    loading.value = false
  }
}

const handleResize = () => {
  chartInstance?.resize()
}

onMounted(() => {
  initChart()
  fetchData()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  chartInstance?.dispose()
})

// 监听主题变化，重新渲染图表
watch(
  () => document.documentElement.className,
  () => {
    if (chartInstance) {
      chartInstance.dispose()
      initChart()
      fetchData()
    }
  }
)
</script>

<style scoped lang="scss">
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart {
  height: 300px;
}
</style> 